package com.loong.user.handler;

import com.loong.common.dynamic.verify.UserVerifyConfig;
import com.loong.common.enumerate.ResultCode;
import com.loong.common.exception.GlobalException;
import com.loong.common.function.CommonConsumer;
import com.loong.common.redis.RedisTools;
import com.loong.common.utils.DESEncrypt;
import com.loong.common.utils.TransformUtils;
import com.loong.common.utils.UUIDUtils;
import com.loong.global.constant.RedisKey;
import com.loong.global.dto.AdminDTO;
import com.loong.global.dto.MemberDTO;
import com.loong.global.dto.UserTokenDTO;
import com.loong.user.business.MemberBusiness;
import com.loong.user.business.UserVerificationBusiness;
import com.loong.user.common.forehead.dto.VerifyDTO;
import com.loong.user.common.forehead.param.login.LoginParam;
import com.loong.user.model.Member;
import com.loong.user.model.UserVerification;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 统一鉴权中心
 */
@Component
public class UserVerificationHandler {


    @Resource
    private UserVerificationBusiness userVerificationBusiness;

    @Resource
    private MemberBusiness memberBusiness;


    /**
     * 普通的密码鉴权获取token
     */
    public void verify(LoginParam loginParam, CommonConsumer<VerifyDTO> check){
        UserVerification verify = userVerificationBusiness.verify(loginParam);
        if(ObjectUtils.isEmpty(verify)) {
            // 用户账号或密码错误
            throw new GlobalException(ResultCode.USER_PASSWORD_ERROR);
        }
        // 生成token
        String uuid = UUIDUtils.getUUID();
        String tokenStr = RedisKey.USER_VERIFY.USER_VERIFY_MEMBER+uuid;
        String desKey = UserVerifyConfig.getConfig().getAdminDesKey();
        String token;
        try {
            token = DESEncrypt.encrypt(tokenStr,desKey);
            // 会员默认七天
            RedisTools.valueOperations().set(token,UserTokenDTO.builder()
                    .deviceNo(loginParam.getHeaderDeviceId())
                    .loginIp(loginParam.getRequestIp())
                    .userId(verify.getId())
                    .userType(verify.getUserType())
                    // todo 从用户设置中获取
                    .build(),7, TimeUnit.DAYS);
        } catch (Exception e) {
           throw new GlobalException("token错误");
        }
        // 修改最后登陆的ip
        verify.setLastLoginIp(loginParam.getRequestIp());
        verify.setLastLoginTime(new Date());
        userVerificationBusiness.save(verify);
        check.apply(VerifyDTO.builder()
                .token(token)
                .userVerification(verify)
                .build());
        // todo 上报登陆日志
        // todo 记录当前在线设备
    }
    public MemberDTO memberLogin(LoginParam loginParam){
        MemberDTO memberDTO = new MemberDTO();
        verify(loginParam,verify->{
            verify.getToken();
            UserVerification userVerification = verify.getUserVerification();
            // 查询会员信息
            MemberDTO cache = RedisTools.valueOperations().get(RedisKey.MEMBER.MEMBER_CACHE + userVerification.getId(), MemberDTO.class);
            TransformUtils.transform(cache,memberDTO);
            memberDTO.setToken(verify.getToken());
        });
        return memberDTO;
    }

    public void adminLogin(LoginParam loginParam){
        verify(loginParam,verify->{
            verify.getToken();
            verify.getUserVerification();
            // 查询admin的信息
        });
    }
    /**
     * 第三方登陆
     * 小程序登陆
     */
    public MemberDTO wxApplet(){
        return new MemberDTO();
    }

}
